using B.S.XZYData.Api.Read.Application.Command.WorkOrder;
using B.S.XZYData.Api.Read.Dto.WorkOrder;
using B.S.XZYData.ErrorCode;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;

namespace B.S.XZYData.Api.Read.Controllers
{
    /// <summary>
    /// 工单读操作控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class WorkOrderController : ControllerBase
    {
        private readonly IMediator _mediator;

        public WorkOrderController(IMediator mediator)
        {
            _mediator = mediator;
        }

        /// <summary>
        /// 获取工单分页列表
        /// </summary>
        /// <param name="index">页码</param>
        /// <param name="size">页大小</param>
        /// <param name="workOrderCode">工单编号（模糊查询）</param>
        /// <param name="productCode">产品编号（模糊查询）</param>
        /// <param name="productName">产品名称（模糊查询）</param>
        /// <param name="spec">产品规格（模糊查询）</param>
        /// <param name="unit">单位</param>
        /// <param name="actualQuantity">实际数量</param>
        /// <param name="status">状态</param>
        /// <param name="plannedStartTimeStart">计划开始时间-开始</param>
        /// <param name="plannedStartTimeEnd">计划开始时间-结束</param>
        /// <param name="plannedEndTimeStart">计划结束时间-开始</param>
        /// <param name="plannedEndTimeEnd">计划结束时间-结束</param>
        /// <param name="actualStartTimeStart">实际开始时间-开始</param>
        /// <param name="actualStartTimeEnd">实际开始时间-结束</param>
        /// <param name="actualEndTimeStart">实际结束时间-开始</param>
        /// <param name="actualEndTimeEnd">实际结束时间-结束</param>
        /// <param name="createTimeStart">创建时间-开始</param>
        /// <param name="createTimeEnd">创建时间-结束</param>
        /// <param name="createBy">创建人</param>
        /// <returns></returns>
        [HttpGet("page")]
        public async Task<ApiPageing<WorkOrderDto>> GetWorkOrderPage(
            [FromQuery] int index = 1,
            [FromQuery] int size = 20,
            [FromQuery] string? workOrderCode = null,
            [FromQuery] string? productCode = null,
            [FromQuery] string? productName = null,
            [FromQuery] string? spec = null,
            [FromQuery] string? unit = null,
            [FromQuery] int? actualQuantity = null,
            [FromQuery] string? status = null,
            [FromQuery] DateTime? plannedStartTimeStart = null,
            [FromQuery] DateTime? plannedStartTimeEnd = null,
            [FromQuery] DateTime? plannedEndTimeStart = null,
            [FromQuery] DateTime? plannedEndTimeEnd = null,
            [FromQuery] DateTime? actualStartTimeStart = null,
            [FromQuery] DateTime? actualStartTimeEnd = null,
            [FromQuery] DateTime? actualEndTimeStart = null,
            [FromQuery] DateTime? actualEndTimeEnd = null,
            [FromQuery] DateTime? createTimeStart = null,
            [FromQuery] DateTime? createTimeEnd = null,
            [FromQuery] string? createBy = null)
        {
            var command = new GetWorkOrderPageCommand
            {
                Index = index,
                Size = size,
                WorkOrderCode = workOrderCode,
                ProductCode = productCode,
                ProductName = productName,
                Spec = spec,
                Unit = unit,
                ActualQuantity = actualQuantity,
                Status = status,
                PlannedStartTimeStart = plannedStartTimeStart,
                PlannedStartTimeEnd = plannedStartTimeEnd,
                PlannedEndTimeStart = plannedEndTimeStart,
                PlannedEndTimeEnd = plannedEndTimeEnd,
                ActualStartTimeStart = actualStartTimeStart,
                ActualStartTimeEnd = actualStartTimeEnd,
                ActualEndTimeStart = actualEndTimeStart,
                ActualEndTimeEnd = actualEndTimeEnd,
                CreateTimeStart = createTimeStart,
                CreateTimeEnd = createTimeEnd,
                CreateBy = createBy
            };

            return await _mediator.Send(command);
        }

        /// <summary>
        /// 获取工单详情（包含工序列表）
        /// </summary>
        /// <param name="id">工单ID</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<ApiResult<WorkOrderDetailDto>> GetWorkOrderDetail(int id)
        {
            var command = new GetWorkOrderDetailCommand
            {
                WorkOrderId = id
            };

            return await _mediator.Send(command);
        }

        /// <summary>
        /// 获取工单综合信息（包含产品信息、工单信息、工序信息、分派信息等完整信息）
        /// </summary>
        /// <param name="id">工单ID</param>
        /// <returns></returns>
        [HttpGet("{id}/comprehensive")]
        public async Task<ApiResult<WorkOrderComprehensiveInfoDto>> GetWorkOrderComprehensiveInfo(int id)
        {
            var command = new GetWorkOrderComprehensiveInfoCommand
            {
                WorkOrderId = id
            };

            return await _mediator.Send(command);
        }

        /// <summary>
        /// 获取所有工单综合信息（按工序展开显示，用于生产报表）
        /// </summary>
        /// <param name="workOrderCode">工单编号（模糊查询）</param>
        /// <param name="productCode">产品编号（模糊查询）</param>
        /// <param name="productName">产品名称（模糊查询）</param>
        /// <param name="processCode">工序编号（模糊查询）</param>
        /// <param name="processName">工序名称（模糊查询）</param>
        /// <param name="workOrderStatus">工单状态筛选</param>
        /// <param name="processStatus">工序状态筛选</param>
        /// <param name="plannedStartTimeStart">计划开始时间-开始</param>
        /// <param name="plannedStartTimeEnd">计划开始时间-结束</param>
        /// <param name="plannedEndTimeStart">计划结束时间-开始</param>
        /// <param name="plannedEndTimeEnd">计划结束时间-结束</param>
        /// <returns></returns>
        [HttpGet("comprehensive/all")]
        public async Task<ApiResult<System.Collections.Generic.List<WorkOrderProcessComprehensiveDto>>> GetAllWorkOrderComprehensiveInfo(
            [FromQuery] string? workOrderCode = null,
            [FromQuery] string? productCode = null,
            [FromQuery] string? productName = null,
            [FromQuery] string? processCode = null,
            [FromQuery] string? processName = null,
            [FromQuery] string? workOrderStatus = null,
            [FromQuery] string? processStatus = null,
            [FromQuery] DateTime? plannedStartTimeStart = null,
            [FromQuery] DateTime? plannedStartTimeEnd = null,
            [FromQuery] DateTime? plannedEndTimeStart = null,
            [FromQuery] DateTime? plannedEndTimeEnd = null)
        {
            var command = new GetAllWorkOrderComprehensiveInfoCommand
            {
                WorkOrderCode = workOrderCode,
                ProductCode = productCode,
                ProductName = productName,
                ProcessCode = processCode,
                ProcessName = processName,
                WorkOrderStatus = workOrderStatus,
                ProcessStatus = processStatus,
                PlannedStartTimeStart = plannedStartTimeStart,
                PlannedStartTimeEnd = plannedStartTimeEnd,
                PlannedEndTimeStart = plannedEndTimeStart,
                PlannedEndTimeEnd = plannedEndTimeEnd
            };

            return await _mediator.Send(command);
        }

        /// <summary>
        /// 获取工序选择列表（用于添加工单时选择工序）
        /// </summary>
        /// <param name="index">页码</param>
        /// <param name="size">页大小</param>
        /// <param name="processCode">工序编号（模糊查询）</param>
        /// <param name="processName">工序名称（模糊查询）</param>
        /// <returns></returns>
        [HttpGet("route-step-select")]
        public async Task<ApiPageing<RouteStepSelectDto>> GetRouteStepSelect(
            [FromQuery] int index = 1,
            [FromQuery] int size = 20,
            [FromQuery] string? processCode = null,
            [FromQuery] string? processName = null)
        {
            var command = new GetRouteStepSelectCommand
            {
                Index = index,
                Size = size,
                ProcessCode = processCode,
                ProcessName = processName
            };

            return await _mediator.Send(command);
        }

        /// <summary>
        /// 导出工单数据
        /// </summary>
        /// <param name="workOrderCode">工单编号（模糊查询）</param>
        /// <param name="productCode">产品编号（模糊查询）</param>
        /// <param name="productName">产品名称（模糊查询）</param>
        /// <param name="spec">产品规格（模糊查询）</param>
        /// <param name="unit">单位</param>
        /// <param name="actualQuantity">实际数量</param>
        /// <param name="status">状态</param>
        /// <param name="plannedStartTimeStart">计划开始时间-开始</param>
        /// <param name="plannedStartTimeEnd">计划开始时间-结束</param>
        /// <param name="plannedEndTimeStart">计划结束时间-开始</param>
        /// <param name="plannedEndTimeEnd">计划结束时间-结束</param>
        /// <param name="actualStartTimeStart">实际开始时间-开始</param>
        /// <param name="actualStartTimeEnd">实际开始时间-结束</param>
        /// <param name="actualEndTimeStart">实际结束时间-开始</param>
        /// <param name="actualEndTimeEnd">实际结束时间-结束</param>
        /// <param name="createTimeStart">创建时间-开始</param>
        /// <param name="createTimeEnd">创建时间-结束</param>
        /// <param name="createBy">创建人</param>
        /// <returns>CSV文件</returns>
        [HttpGet("export")]
        public async Task<IActionResult> ExportWorkOrder(
            [FromQuery] string? workOrderCode = null,
            [FromQuery] string? productCode = null,
            [FromQuery] string? productName = null,
            [FromQuery] string? spec = null,
            [FromQuery] string? unit = null,
            [FromQuery] int? actualQuantity = null,
            [FromQuery] string? status = null,
            [FromQuery] DateTime? plannedStartTimeStart = null,
            [FromQuery] DateTime? plannedStartTimeEnd = null,
            [FromQuery] DateTime? plannedEndTimeStart = null,
            [FromQuery] DateTime? plannedEndTimeEnd = null,
            [FromQuery] DateTime? actualStartTimeStart = null,
            [FromQuery] DateTime? actualStartTimeEnd = null,
            [FromQuery] DateTime? actualEndTimeStart = null,
            [FromQuery] DateTime? actualEndTimeEnd = null,
            [FromQuery] DateTime? createTimeStart = null,
            [FromQuery] DateTime? createTimeEnd = null,
            [FromQuery] string? createBy = null)
        {
            var command = new ExportWorkOrderCommand
            {
                Code = workOrderCode,
                ProductCode = productCode,
                ProductName = productName,
                Spec = spec,
                Unit = unit,
                ActualQuantity = actualQuantity,
                Status = status,
                PlannedStartTimeStart = plannedStartTimeStart,
                PlannedStartTimeEnd = plannedStartTimeEnd,
                PlannedEndTimeStart = plannedEndTimeStart,
                PlannedEndTimeEnd = plannedEndTimeEnd,
                ActualStartTimeStart = actualStartTimeStart,
                ActualStartTimeEnd = actualStartTimeEnd,
                ActualEndTimeStart = actualEndTimeStart,
                ActualEndTimeEnd = actualEndTimeEnd,
                CreateTimeStart = createTimeStart,
                CreateTimeEnd = createTimeEnd,
                CreateBy = createBy
            };

            var result = await _mediator.Send(command);

            if (result.Code == ApiEnum.Success)
            {
                var fileName = $"工单数据导出_{DateTime.Now:yyyyMMddHHmmss}.csv";
                return File(result.Data, "text/csv; charset=utf-8", fileName);
            }
            else
            {
                return BadRequest(result);
            }
        }
    }
}
